package jblip.gui.components;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JScrollPane;
import javax.swing.JSplitPane;

import jblip.gui.JBlip;
import jblip.gui.components.view.UpdateChannelPanel;
import jblip.gui.data.channels.UpdatesDataChannel;
import jblip.gui.data.channels.UserDataChannel;
import jblip.gui.data.images.ImageCache;
import jblip.resources.Media;

public class ActionPanel extends JSplitPane implements Observer {
  private static final long serialVersionUID = 1L;

  private final Map<UpdatesDataChannel, UpdateChannelPanel> channel_panels;

  private final JScrollPane view_panel;

  private final InputPanel input_panel;

  public ActionPanel() {
    super(JSplitPane.VERTICAL_SPLIT);
    view_panel = new JScrollPane();
    input_panel = new InputPanel();
    add(view_panel, JSplitPane.TOP);
    add(input_panel, JSplitPane.BOTTOM);
    setDividerSize(2);
    setResizeWeight(1.0);

    channel_panels = new HashMap<UpdatesDataChannel, UpdateChannelPanel>();
  }

  private void viewChannel(final UpdatesDataChannel channel) {
    UpdateChannelPanel panel = channel_panels.get(channel);
    if (panel == null) {
      panel = new UpdateChannelPanel();
      channel.addObserver(panel, UpdateChannelPanel.INITIAL_SIZE);
      channel_panels.put(channel, panel);
      if (channel instanceof UserDataChannel) {
        setUserPanelBackround((UserDataChannel) channel, panel);
      }
    }
    view_panel.setViewportView(panel);
    input_panel.setChannel(channel);
  }
  
  private void setUserPanelBackround(final UserDataChannel channel,
      final UpdateChannelPanel panel) {
    final String uname = channel.getUserName();
    final ImageCache cache = JBlip.instance().getImageCache();
    final Media bg = JBlip.instance().getBlipClient().getBackground(uname);
    if (bg != null) {
      try {
        cache.getImage(new URL(bg.getURL()), panel);
      } catch (MalformedURLException e) {
        // Blip API gave us wrong URL?
        e.printStackTrace();
      }
    }
  }

  @Override
  public void update(Observable o, Object arg) {
    if (arg instanceof UpdatesDataChannel) {
      viewChannel((UpdatesDataChannel) arg);
    }
  }
}
